﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Media.Imaging;
using System.Diagnostics;
using ManYor.Phone.Common;
using System.Windows.Controls.Primitives;
using System.IO.IsolatedStorage;
using Microsoft.Xna.Framework.Media;
using System.IO;

namespace ManYor
{
    public partial class SliderShow :PhoneApplicationPage
    {
        #region -- Private Field --
        private const int IMAGE_WIDTH = 480;
        /// <summary>
        /// 页面通知对象
        /// </summary>
        private PageNotify pNotify;
        /// <summary>
        /// 当前图片对象
        /// </summary>
       private Image ImgZoom;
        /// <summary>
        /// 缓存的图片数据源数组
        /// </summary>
        private List<Image> cachedImage;
       
        /// <summary>
        /// 图片数据源数组
        /// </summary>
        private IList<CommicFrame> frames;

        //默认图片Index
        private int currentIndex = 0;       
        #endregion
        /// <summary>
        /// 构造器
        /// </summary>
        public SliderShow():base()
        {
            InitializeComponent();
            pNotify=new PageNotify(this);
            this.Loaded += new RoutedEventHandler(SliderShow_Loaded);
           
        }
        /// <summary>
        /// 页面载入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SliderShow_Loaded(object sender, RoutedEventArgs e)          
        {           
            frames = new List<CommicFrame>() { new CommicFrame() { Source = "Images/01.jpg" },
                                                new CommicFrame() { Source = "Images/02.jpg" },
                                                new CommicFrame() { Source = "Images/03.jpg" },
                                                new CommicFrame() { Source = "Images/04.jpg" },
                                                new CommicFrame() { Source = "Images/05.jpg" },
                                                new CommicFrame() { Source = "Images/06.jpg" },
                                                new CommicFrame() { Source = "Images/07.jpg" }};

            BitmapImage bi = new BitmapImage(new Uri(frames[0].Source, UriKind.Relative));
            ImageSlider.Source = bi;
            ImageSliderBg.Source = bi;

            ImgZoom = this.ImageSlider;
            //初始化图片缩放事件
            InitializeMultiPointEvent();
            ProgressText.Text = string.Format("{0}/{1}", currentIndex + 1, frames.Count());
        }

        /// <summary>
        /// 初始化多点缩放事件
        /// </summary>
        private void InitializeMultiPointEvent()
        {
            var gs = GestureService.GetGestureListener(this.ImgZoom);
            gs.PinchStarted += new EventHandler<PinchStartedGestureEventArgs>(OnPinchStarted);
            gs.PinchDelta += new EventHandler<PinchGestureEventArgs>(OnPinchDelta);
            gs.DragDelta += new EventHandler<DragDeltaGestureEventArgs>(OnDragDelta);
            gs.Tap += new EventHandler<Microsoft.Phone.Controls.GestureEventArgs>(OnTap);
            gs.DoubleTap += new EventHandler<Microsoft.Phone.Controls.GestureEventArgs>(OnDoubleTap);
            gs.Flick += new EventHandler<FlickGestureEventArgs>(OnFlick);
        }

        /// <summary>
        /// 点击出现菜单栏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnTap(object sender, Microsoft.Phone.Controls.GestureEventArgs e)
        {            
            if (this.ApplicationBar.IsVisible)
            {
                InfoBarFadeOut.Begin();
            }
            else
            {
                InfoBarFadeIn.Begin();
            }
            this.ApplicationBar.IsVisible = !this.ApplicationBar.IsVisible;            
        }
        /// <summary>
        /// 手指扫动事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnFlick(object sender, FlickGestureEventArgs e)
        {           
            if (TotalImageScale > 1.1F)
            {               
                return;
            }
            else
            {
                TotalImageScale = 1.0F;
                ResetImagePosition();
                JumpNextFrame(e.HorizontalVelocity<0);
                ProgressText.Text = string.Format("{0}/{1}", currentIndex + 1, frames.Count());
            }          
        }
        /// <summary>
        /// 跳到下一帧
        /// </summary>
        /// <param name="isNext"></param>
        private void JumpNextFrame(bool isNext)
        {
            //向后
            if (isNext)
            {
                if (currentIndex + 1 < frames.Count())
                {                    
                    BitmapImage bi = new BitmapImage(new Uri(frames[++currentIndex].Source, UriKind.Relative));
                    ImageSlider.Source = bi;
                    boarderFadeNext.Begin();
                }
                else
                {
                    //到了最末页
                    pNotify.ShowPopup("已经到了最后一页");
                }
            }
            else
            {
                if (currentIndex >= 1)
                {
                    BitmapImage bi = new BitmapImage(new Uri(frames[--currentIndex].Source, UriKind.Relative));
                    ImageSlider.Source = bi;
                    boarderFadePre.Begin();
                }
                else
                {
                    //到了首页
                    pNotify.ShowPopup("已经到了第一页");
                }
            }
        }
        /// <summary>
        /// 动画执行完毕,将底图更改为当前的图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FadeStoryboard_Completed(object sender, EventArgs e)
        {
            BitmapImage bi = new BitmapImage(new Uri(frames[currentIndex].Source, UriKind.Relative));
            ImageSliderBg.Source = bi;
        }
        
        /// <summary>
        /// 重新开始阅读
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ResetIndex_Click(object sender, EventArgs e)
        {
            MessageBoxResult result= MessageBox.Show("重新阅读将不会保存当前阅读进度，是否确定从第一页开始重新阅读？", "确定", MessageBoxButton.OKCancel);
            if (result == MessageBoxResult.OK)
            {
                currentIndex = 1;
                BitmapImage bi = new BitmapImage(new Uri(frames[0].Source, UriKind.Relative));
                ImageSlider.Source = bi;
                ImageSliderBg.Source = bi;
                ProgressText.Text = string.Format("{0}/{1}", currentIndex , frames.Count());
            }
        }
        /// <summary>
        /// 保存到相册
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Save_Click(object sender, EventArgs e)
        {
            try
            {
                //BitmapImage bi = new BitmapImage(new Uri(frames[0].Source, UriKind.Relative));
               
                ////StreamReader sr=new StreamReader(
                ////byte[] bytes=new byte
                //    MediaLibrary library = new MediaLibrary();
                //    string saveFileName = "0_" + frames[currentIndex].Source.Replace("/", "");
                //    library.SavePicture(saveFileName + "", stream);

                pNotify.ShowPopup("已保存到相册");
            }
            catch
            {
                MessageBox.Show("保存到相册失败！");
            }
        }

       
    }
}